package com.quiz.bis.util.pdf;

import com.lowagie.text.Font;
import com.lowagie.text.pdf.BaseFont;
import com.quiz.common.exception.ServiceException;
import com.quiz.common.utils.file.FileUtils;
import lombok.extern.slf4j.Slf4j;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.springframework.util.ResourceUtils;
import org.xhtmlrenderer.pdf.ITextRenderer;

import javax.servlet.http.HttpServletResponse;

/**
 * pdf工具类
 *
 * @author ahuan
 */
@Slf4j
public class PdfUtil {

    private static String FONT_PATH = null;
    private static BaseFont baseFont = null;

//    static {
//        try {
//            FONT_PATH =
//        } catch (Exception e) {
//            try {
//                // 备用字体
//                baseFont = BaseFont.createFont("STSong-Light", "UniGB-UCS2-H", BaseFont.EMBEDDED);
//            } catch (Exception ex) {
//                ex.printStackTrace();
//            }
//        }
//    }

//    public static class ChineseFontProvider extends XMLWorkerFontProvider {
//        public ChineseFontProvider() {
//            super(null, null);
//        }
//
//        public Font getFont(String fontname, String encoding,
//                            boolean embedded, float size, int style) {
//            try {
//                BaseFont bf = BaseFont.createFont(FONT_PATH,
//                        BaseFont.IDENTITY_H,
//                        BaseFont.EMBEDDED);
//                return new Font(bf, size, style);
//            } catch (Exception e) {
//                return super.getFont(fontname, encoding, embedded, size, style,null);
//            }
//        }
//    }
    /**
     * 导出PDF
     *
     * @param html HTML模版
     */
    public static void exportToPdf(String html, String fileName, HttpServletResponse response) {
        try {
            FileUtils.setAttachmentResponseHeader(response, fileName);
            response.setContentType("application/octet-stream");

            // 修复 HTML，确保符合 XML 规范
            Document doc = Jsoup.parse(html);
            doc.outputSettings().syntax(Document.OutputSettings.Syntax.xml); // 强制 XHTML 格式
            String xhtml = doc.html();

            ITextRenderer renderer = new ITextRenderer();
            addChineseFontSupport(renderer);
            renderer.setDocumentFromString(xhtml); // 使用修复后的 XHTML
            renderer.layout();
            renderer.createPDF(response.getOutputStream());

        } catch (Exception e) {
            throw new RuntimeException("导出PDF失败", e);
        }
    }


    public static Font getChineseFont(float size, int style) {
        try {
            String path = ResourceUtils.getURL("classpath:fonts/simsun.ttc").getPath();
            baseFont = BaseFont.createFont(path + ",1", BaseFont.IDENTITY_H, BaseFont.EMBEDDED);
            return new Font(baseFont, size, style);
        }catch (Exception e) {
            log.error("加载中文字体失败", e);
            throw new ServiceException("加载中文字体失败");
        }
    }




    private static void addChineseFontSupport(ITextRenderer renderer) {
        try {
            // 方式1：使用系统字体
            // String fontPath = "/usr/share/fonts/chinese/SimSun.ttf"; // Linux系统路径示例
            // 或 Windows路径示例：C:/Windows/Fonts/simsun.ttc

            // 方式2：使用resources目录下的字体（需将字体文件放入resources/fonts）
            // String fontPath = this.getClass().getResource("/fonts/simsun.ttf").getPath();

            // renderer.getFontResolver().addFont(fontPath,
            //        BaseFont.IDENTITY_H,
            //        BaseFont.EMBEDDED); // 必须使用EMBEDDED

            String fontPath = ResourceUtils.getURL("classpath:fonts/simsun.ttc").getPath();
            // 备用字体设置
            renderer.getFontResolver().addFont(
                    fontPath,
                    BaseFont.IDENTITY_H,
                    BaseFont.EMBEDDED
            );
        } catch (Exception e) {
            log.error("加载中文字体失败", e);
            throw new ServiceException("加载中文字体失败");
        }
    }
}
